package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.TwoNetwork;
import com.example.demo.entity.TwoNetwork2;
import com.example.demo.entity.TwoNetwork2;
import com.example.demo.entity.TwoNetwork;
import com.example.demo.entity.TwoNetwork2;
import com.example.demo.form.TwoNetworkForm;
import com.example.demo.form.TwoNetworkForm;
import com.example.demo.service.TwoNetwork2Service;
import com.example.demo.service.TwoNetworkService;

@RestController
@RequestMapping(value = "/twonetwork2")
public class TwoNetwork2Controller {
	@Autowired
	private TwoNetwork2Service service2;
	@Autowired 
	private TwoNetworkService service1;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");

	
	@RequestMapping(value = "/save")
	private Object save(TwoNetworkForm Form) throws ParseException {
		Integer saleId1 = Form.getId();
		Date d= new Date();
		Date d1 = dateFormat1.parse("1999-01-01");
		TwoNetwork sale1= new TwoNetwork();
		TwoNetwork Sale1= new TwoNetwork();
		TwoNetwork2 sale2= new TwoNetwork2();
		TwoNetwork2 Sale2= new TwoNetwork2();
		if(saleId1==null) {
			Sale1.setName(Form.getName());
			sale1 = service1.save(Sale1);
		}else {
			 sale1 = service1.findById(saleId1);
			 sale1.setName(Form.getName());
			 service1.save(sale1);
				List<TwoNetwork2> list = service2.findByTwoNetId(sale1.getId());
				for (TwoNetwork2 TwoNetwork2 : list) {
					if(d1.compareTo(TwoNetwork2.getBeginDate())==-1) {
						d1=TwoNetwork2.getBeginDate();
						Sale2=TwoNetwork2;
					}
				}
				Sale2.setEndDate(d);
				service2.save(Sale2);
				
		}
		BeanUtils.copyProperties(Form, sale2, "id","name");
		sale2.setTwoNet(sale1);
		sale2.setBeginDate(d);
		service2.save(sale2);
		return new AjaxResult("数据保存成功");			
	}
	
	@RequestMapping(value = "/list")
	public Object list() {
		return new AjaxResult(service1.findAll());
	}
	
	
	@RequestMapping(value = "/findbyId")
	public Object findbyId(Integer id) throws ParseException {
		List<TwoNetwork2> list=service2.findByTwoNetId(id);
		DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		Date d = dateFormat1.parse("1999-01-01");
		TwoNetwork2 yan=new TwoNetwork2();
		for(TwoNetwork2 y :list) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				yan=y;
			}
		}
		return new AjaxResult(yan);
	}
	
	
}
